package com.zjc.springboot.nettyclient.channelInitializer;

import com.zjc.springboot.nettyclient.client.NettyClient;
import com.zjc.springboot.nettyclient.client.NettyClient12;
import com.zjc.springboot.nettyclient.client.NettyClient15;
import com.zjc.springboot.nettyclient.handler.Msg12Handler;
import com.zjc.springboot.nettyclient.handler.Msg15Handler;
import com.zjc.springboot.nettyclient.handler.NettyClientHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

public class NettyChannelInitializer extends ChannelInitializer {

    private NettyClient nettyClient;

    public NettyChannelInitializer(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    @Override
    protected void initChannel(Channel channel) {
        channel.pipeline().addLast(new IdleStateHandler(20, 10, 0));
        channel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
        channel.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
        channel.pipeline().addLast(new NettyClientHandler(nettyClient));

        if (nettyClient instanceof NettyClient12) {
            channel.pipeline().addLast(new Msg12Handler(nettyClient));
        }
        if (nettyClient instanceof NettyClient15) {
            channel.pipeline().addLast(new Msg15Handler(nettyClient));
        }
    }
}
